package com.bjpowernode.listeners;

import cn.hutool.json.JSONUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.bjpowernode.mappers.TClueMapper;
import com.bjpowernode.excels.ClueExcel;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.List;

@Slf4j
public class ClueExcelListener implements ReadListener<ClueExcel> {
    private static final int BATCH_COUNT = 100;
    private List<ClueExcel> clueDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private TClueMapper tClueMapper;
    private Integer loginUserId;

    public ClueExcelListener() {
    }

    public ClueExcelListener(TClueMapper tClueMapper, Integer loginUserId) {
        this.tClueMapper = tClueMapper;
        this.loginUserId = loginUserId;
    }

    @Override
    public void invoke(ClueExcel data, AnalysisContext context) {
        data.setCreateTime(new Date());
        data.setCreateBy(loginUserId);
        log.info("解析到一条数据:{}", JSONUtil.toJsonStr(data));
        clueDataList.add(data);
        if (clueDataList.size() >= BATCH_COUNT) {
            saveData();
            clueDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据解析完成！");
    }

    private void saveData() {
        log.info("{}条数据，开始存储数据库！", clueDataList.size());
        tClueMapper.saveExcel(clueDataList);
        log.info("存储数据库成功！");
    }
}
